package com.blog.service.impl;

import com.blog.pojo.Article;
import com.blog.pojo.RawNews;
import com.blog.pojo.SimpleNews;
import com.blog.service.ArticleService;
import com.blog.service.NewsSpiderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;



@Service
public class NewsSpiderServiceImpl implements NewsSpiderService {

    @Autowired
    private ArticleService newsService;

    /**
     * 将新闻转为文章格式保存
     * @param news 新闻
     * @return 是否成功保存
     */
    @Override
    public String publishNews(SimpleNews news) {
       Integer id = Integer.valueOf(news.getId());
       String author = "admin"; // 只有管理员能爬取新闻

        String articleContent = news.getTitle();
        String articleTitle = null;

        //这里的【】和（） 截取不正常，只有左边。应该是两个都有
       if(articleContent.contains("【")){
            StringBuilder sb = new StringBuilder();
            sb.append("[爬取]");
            int index1 = articleContent.indexOf("【")+1;
            int index2 = articleContent.indexOf("】");
            sb.append(articleContent.substring(index1,index2));
           articleTitle = sb.toString();
       }else{
           articleTitle = "[爬取]"+id;
       }

        String articleType = "爬取";

        String articleTags = null;
       if (articleContent.endsWith("）")){
           articleTags = articleContent.substring(articleContent.lastIndexOf("（")+1,articleContent.lastIndexOf("）"));
       }else{
           articleTags = "新浪新闻";
       }


       String time = news.getDate_modified();
       StringBuilder sb = new StringBuilder();
       String publishDate =sb.append(time.substring(0,9)).append(" ").append(time.substring(11,18)).toString();

        String updateDate = publishDate;
        int likes = 0 ;

        Article article1 = new Article();
        article1.setArticleTags(articleTags);
        article1.setArticleTitle(articleTitle);
        article1.setArticleType(articleType);
        article1.setArticleContent(articleContent);
        article1.setPublishDate(publishDate);
        article1.setAuthor(author);
        article1.setId(id);
        article1.setLikes(likes);
        article1.setUpdateDate(updateDate);

        article1.setRawnewsid(Integer.parseInt(news.getId()));

        int i = newsService.addArticle(article1);
        if (i>0) {
            return "发表成功";
        }
        return "发表失败";

    }

}
